package com.english.controller.admin;

import com.english.entity.ClassAttendance;
import com.english.entity.AttendanceLog;
import com.english.service.AttendanceService;
import com.english.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员签到签退控制器
 *
 * @author wlq
 * @since 2025-08-08
 */
@RestController
@RequestMapping("/api/attendance")
public class AdminAttendanceController extends AdminBaseController {

    @Autowired
    private AttendanceService attendanceService;

    /**
     * 学生签到
     */
    @PostMapping("/signin")
    public Map<String, Object> signIn(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 从token获取管理员ID
            String token = httpRequest.getHeader("Authorization");
            Long adminId = getAdminId(token);
            
            Long studentId = Long.valueOf(request.get("studentId").toString());
            
            Map<String, Object> result = attendanceService.signIn(studentId, adminId);
            
            if ((Boolean) result.get("success")) {
                response.put("code", 200);
                response.put("message", result.get("message"));
                response.put("data", result);
            } else {
                response.put("code", 400);
                response.put("message", result.get("message"));
            }
            
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "签到失败：" + e.getMessage());
        }
        
        return response;
    }

    /**
     * 学生签退
     */
    @PostMapping("/signout")
    public Map<String, Object> signOut(@RequestBody Map<String, Object> request, HttpServletRequest httpRequest) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 从token获取管理员ID
            String token = httpRequest.getHeader("Authorization");
            Long adminId = getAdminId(token);
            
            Long studentId = Long.valueOf(request.get("studentId").toString());
            
            Map<String, Object> result = attendanceService.signOut(studentId, adminId);
            
            if ((Boolean) result.get("success")) {
                response.put("code", 200);
                response.put("message", result.get("message"));
                response.put("data", result);
            } else {
                response.put("code", 400);
                response.put("message", result.get("message"));
            }
            
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "签退失败：" + e.getMessage());
        }
        
        return response;
    }

    /**
     * 获取今日签到记录
     */
    @GetMapping("/today")
    public Map<String, Object> getTodayAttendance(
            @RequestParam(value = "date", required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            if (date == null) {
                date = LocalDate.now();
            }
            
            List<ClassAttendance> attendanceList = attendanceService.getTodayAttendance(date);
            
            // 转换为前端需要的格式
            List<Map<String, Object>> formattedList = attendanceList.stream()
                    .map(attendance -> {
                        Map<String, Object> item = new HashMap<>();
                        item.put("studentId", attendance.getStudentId());
                        item.put("status", attendance.getStatus().name().toLowerCase().replace("_", "-"));
                        item.put("signInTime", attendance.getSignInTime());
                        item.put("signOutTime", attendance.getSignOutTime());
                        item.put("studentName", attendance.getStudentName());
                        item.put("className", attendance.getClassName());
                        return item;
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            response.put("code", 200);
            response.put("message", "获取成功");
            response.put("data", formattedList);
            
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "获取今日签到记录失败：" + e.getMessage());
        }
        
        return response;
    }

    /**
     * 获取学生签到历史
     */
    @GetMapping("/history")
    public Map<String, Object> getStudentAttendanceHistory(@RequestParam("studentId") Long studentId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<ClassAttendance> historyList = attendanceService.getStudentAttendanceHistory(studentId);
            
            // 转换为前端需要的格式
            List<Map<String, Object>> formattedList = historyList.stream()
                    .map(attendance -> {
                        Map<String, Object> item = new HashMap<>();
                        item.put("id", attendance.getId());
                        item.put("type", attendance.getStatus() == ClassAttendance.AttendanceStatus.SIGNED_IN ? "checkin" : "checkout");
                        item.put("time", attendance.getSignInTime() != null ? attendance.getSignInTime() : attendance.getSignOutTime());
                        item.put("adminName", attendance.getAdminName() != null ? attendance.getAdminName() : "管理员");
                        item.put("date", attendance.getAttendanceDate());
                        return item;
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            response.put("code", 200);
            response.put("message", "获取成功");
            response.put("data", formattedList);
            
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "获取签到历史失败：" + e.getMessage());
        }
        
        return response;
    }

    /**
     * 获取今日签到统计
     */
    @GetMapping("/stats")
    public Map<String, Object> getTodayStats(
            @RequestParam(value = "date", required = false) 
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            if (date == null) {
                date = LocalDate.now();
            }
            
            Map<String, Object> stats = attendanceService.getTodayStats(date);
            
            response.put("code", 200);
            response.put("message", "获取成功");
            response.put("data", stats);
            
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "获取统计信息失败：" + e.getMessage());
        }
        
        return response;
    }

    /**
     * 获取学生签到签退日志
     */
    @GetMapping("/logs/student/{studentId}")
    public R<List<Object>> getStudentAttendanceLogs(@PathVariable Long studentId) {
        try {
            List<AttendanceLog> logs = attendanceService.getStudentAttendanceLogs(studentId);
            
            List<Object> result = logs.stream().map(log -> {
                Map<String, Object> logMap = new HashMap<>();
                logMap.put("id", log.getId());
                logMap.put("studentId", log.getStudentId());
                logMap.put("adminId", log.getAdminId());
                logMap.put("attendanceId", log.getAttendanceId());
                logMap.put("actionType", log.getActionType().name().toLowerCase().replace("_", "-"));
                logMap.put("actionTime", log.getActionTime());
                logMap.put("hoursDeducted", log.getHoursDeducted());
                logMap.put("beforeRemainingHours", log.getBeforeRemainingHours());
                logMap.put("afterRemainingHours", log.getAfterRemainingHours());
                logMap.put("notes", log.getNotes());
                return logMap;
            }).collect(java.util.stream.Collectors.toList());
            
            return R.success("获取成功", result);
        } catch (Exception e) {
            return R.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 获取今日签到签退日志
     */
    @GetMapping("/logs/today")
    public R<List<Object>> getTodayAttendanceLogs(@RequestParam LocalDate date) {
        try {
            List<AttendanceLog> logs = attendanceService.getTodayAttendanceLogs(date);
            
            List<Object> result = logs.stream().map(log -> {
                Map<String, Object> logMap = new HashMap<>();
                logMap.put("id", log.getId());
                logMap.put("studentId", log.getStudentId());
                logMap.put("adminId", log.getAdminId());
                logMap.put("attendanceId", log.getAttendanceId());
                logMap.put("actionType", log.getActionType().name().toLowerCase().replace("_", "-"));
                logMap.put("actionTime", log.getActionTime());
                logMap.put("hoursDeducted", log.getHoursDeducted());
                logMap.put("beforeRemainingHours", log.getBeforeRemainingHours());
                logMap.put("afterRemainingHours", log.getAfterRemainingHours());
                logMap.put("notes", log.getNotes());
                return logMap;
            }).collect(java.util.stream.Collectors.toList());
            
            return R.success("获取成功", result);
        } catch (Exception e) {
            return R.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 获取最近的签到签退日志
     */
    @GetMapping("/logs/recent")
    public R<List<Object>> getRecentAttendanceLogs(@RequestParam(defaultValue = "50") Integer limit) {
        try {
            List<AttendanceLog> logs = attendanceService.getRecentAttendanceLogs(limit);
            
            List<Object> result = logs.stream().map(log -> {
                Map<String, Object> logMap = new HashMap<>();
                logMap.put("id", log.getId());
                logMap.put("studentId", log.getStudentId());
                logMap.put("adminId", log.getAdminId());
                logMap.put("attendanceId", log.getAttendanceId());
                logMap.put("actionType", log.getActionType().name().toLowerCase().replace("_", "-"));
                logMap.put("actionTime", log.getActionTime());
                logMap.put("hoursDeducted", log.getHoursDeducted());
                logMap.put("beforeRemainingHours", log.getBeforeRemainingHours());
                logMap.put("afterRemainingHours", log.getAfterRemainingHours());
                logMap.put("notes", log.getNotes());
                return logMap;
            }).collect(java.util.stream.Collectors.toList());
            
            return R.success("获取成功", result);
        } catch (Exception e) {
            return R.error("获取失败：" + e.getMessage());
        }
    }
} 